import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { resetRouter } from '@/router'
import { login as loginApi } from '@/apis'
import { setToken, clearToken, getToken } from '@/utils/auth'

const storeSetup = () => {
  const userInfo = reactive({
    name: '',
    avatar: '',
    rewardChannelStr: ''
  })
  const userName = computed(() => userInfo.name)
  const avatar = computed(() => userInfo.avatar)

  const token = ref<string>(getToken() || '')
  const roles = ref<string[]>([]) // 当前用户角色
  const permissions = ref<string[]>([]) // 当前角色权限标识集合

  const rewardChannelStr = localStorage.getItem('rewardChannelStr')
  if (rewardChannelStr) {
    userInfo.rewardChannelStr = rewardChannelStr
  }

  // 重置token
  const resetToken = () => {
    token.value = ''
    clearToken()
  }

  // 登录
  const login = async (params: any) => {
    const res = await loginApi(params)
    setToken(res.data)
    token.value = res.data
  }

  const setRewardChannelStr = async (params: string) => {
    userInfo.rewardChannelStr = params
    localStorage.setItem('rewardChannelStr', params)
  }

  // 退出
  const logout = () => {
    token.value = ''
    roles.value = []
    permissions.value = []
    clearToken()
    resetRouter()
  }

  // 获取用户信息
  const getInfo = () => {
    userInfo.name = localStorage.getItem('name') || 'admin'
    userInfo.avatar = localStorage.getItem('avatar') || ''
    roles.value = ['user']
  }

  return {
    userInfo,
    userName,
    avatar,
    token,
    roles,
    permissions,
    login,
    logout,
    getInfo,
    resetToken,
    setRewardChannelStr
  }
}

export const useUserStore = defineStore('user', storeSetup, { persist: { paths: ['token'], storage: localStorage } })
